package com.huaxiafinance.management.service.impl;

import com.huaxiafinance.management.constant.CommonConstant;
import com.huaxiafinance.management.dto.request.HandleDto;
import com.huaxiafinance.management.dto.request.WithdrawalsDto;
import com.huaxiafinance.management.mapper.PartnerCommissionMapper;
import com.huaxiafinance.management.mapper.PartnerInfoMapper;
import com.huaxiafinance.management.mapper.PartnerWithdrawalsMapper;
import com.huaxiafinance.management.mapper.YfqDictionaryMapper;
import com.huaxiafinance.management.model.PartnerCommission;
import com.huaxiafinance.management.model.PartnerInfo;
import com.huaxiafinance.management.model.PartnerWithdrawals;
import com.huaxiafinance.management.service.PresentProcessingService;
import com.huaxiafinance.management.util.DateUtil;
import com.huaxiafinance.management.util.MessageResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by huangwencheng on 2017/12/05.
 */
@Service("presentProcessingService")
@SuppressWarnings("SpringJavaAutowiringInspection")
@Transactional
public class PresentProcessingServiceImpl implements PresentProcessingService {

    private static final Logger log = Logger.getLogger(PresentProcessingServiceImpl.class);

    @Autowired
    private YfqDictionaryMapper yfqDictionaryMapper;

    @Autowired
    private PartnerWithdrawalsMapper partnerWithdrawalsMapper;

    @Autowired
    private PartnerInfoMapper partnerInfoMapper;

    @Autowired
    private PartnerCommissionMapper partnerCommissionMapper;

    /**
     * 获取提现处理状态名称列表
     *
     * @return
     * @throws Exception
     */
    @Override
    public MessageResult queryStateList() throws Exception {
        MessageResult messageResult = new MessageResult();
        List<Map<String, Object>> map = yfqDictionaryMapper.selectDictList(CommonConstant.PRESENT_HANDLE);
        messageResult.setData(map);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 获取处理列表
     *
     * @param dto
     * @return
     * @throws Exception
     */
    @Override
    public MessageResult queryWithdrawals(HandleDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
        int countSum = 0;
        if (dto.getStartTime() != null && dto.getEndTime() != null &&
                !("").equals(dto.getStartTime()) &&
                !("").equals(dto.getEndTime())) {
            Map<String, Date> map = DateUtil.getTimeFormat(dto.getStartTime(), dto.getEndTime());
            dto.setStartDate(map.get("beginTime"));
            dto.setEndDate(map.get("overTime"));
        } else {
            dto.setStartTime(null);
            dto.setEndTime(null);
        }
        dto.setPage(dto.getPage() * dto.getRows());
        List<PartnerWithdrawals> partnerWithdrawalsList = partnerWithdrawalsMapper.queryAll(dto);
        countSum = partnerWithdrawalsMapper.count(dto);
        messageResult.setRows(countSum);
        messageResult.setData(partnerWithdrawalsList);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 获取提现详情
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public MessageResult queryWithdrawalsDetails(String id) throws Exception {
        MessageResult messageResult = new MessageResult();
        if (id==null||("").equals(id)){
            messageResult.setFailureResult("id不能为空");
            return messageResult;
        }
        Integer withdrawalsId = Integer.parseInt(id);
        PartnerWithdrawals partnerWithdrawals = partnerWithdrawalsMapper.selectById(withdrawalsId);
        messageResult.setData(partnerWithdrawals);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 修改提现申请
     *
     * @param dto
     * @return
     * @throws Exception
     */
    @Override
    public MessageResult updateWithdrawals(WithdrawalsDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
        synchronized (this){
            PartnerWithdrawals partnerWithdrawals = partnerWithdrawalsMapper.selectByPrimaryKey(dto.getId());
            if (partnerWithdrawals==null){
                messageResult.setFailureResult("该提现已不存在");
                return messageResult;
            }
            PartnerInfo partnerInfo = partnerInfoMapper.selectByUserUuid(partnerWithdrawals.getUserUuid());
            if (partnerInfo==null){
                messageResult.setFailureResult("不存在该用户");
                return messageResult;
            }
            //修改凭证
            if (dto.getRequestType()==1){
                if (partnerWithdrawals.getHandleStatus()!=2){
                    messageResult.setFailureResult("提现状态不处于当前状态，请重新刷新");
                    return messageResult;
                }
                //判断路径和地址
                if (dto.getVoucherUrl()==null||dto.getVoucherName()==null){
                    messageResult.setFailureResult("凭证不能为空");
                    return messageResult;
                }
                partnerWithdrawals.setVoucherUrl(dto.getVoucherUrl());
                partnerWithdrawals.setVoucherName(dto.getVoucherName());
                partnerWithdrawals.setHandlePerId(dto.getAdminId());
                partnerWithdrawals.setHandleTime(new Date());
                int updateResult = partnerWithdrawalsMapper.updateByPrimaryKeySelective(partnerWithdrawals);
                if (updateResult!=1){
                    messageResult.setFailureResult("提交失败，重新提交");
                    return messageResult;
                }
            }//提现成功
            else if (dto.getRequestType()==2){
                //判断提现状态   3-审核通过 1-待处理
                if (partnerWithdrawals.getAuditStatus()!=3
                        ||partnerWithdrawals.getHandleStatus()!=1){
                    messageResult.setFailureResult("提现状态不处于当前状态，请重新刷新");
                    return messageResult;
                }
                //当状态为1退审
                if (dto.getType()==1){
                    //判断退审理由是否为空
                    if (dto.getReturnedReason()==null||("").equals(dto.getReturnedReason()) ){
                        messageResult.setFailureResult("退审理由不能为空");
                        return messageResult;
                    }
                    partnerWithdrawals.setReturnedReason(dto.getReturnedReason());
                    partnerWithdrawals.setAuditStatus(2);
                    partnerWithdrawals.setHandlePerId(dto.getAdminId());
                    partnerWithdrawals.setHandleTime(new Date());
                    int updateResult = partnerWithdrawalsMapper.updateByPrimaryKeySelective(partnerWithdrawals);
                    if (updateResult!=1){
                        messageResult.setFailureResult("提交失败，重新提交");
                        return messageResult;
                    }
                }//判断状态为0 提现
                else if(dto.getType()==0){
                    //2-已打款
                    partnerWithdrawals.setHandleStatus(2);
                    partnerWithdrawals.setHandleTime(new Date());
                    partnerWithdrawals.setHandlePerId(dto.getAdminId());
                    partnerWithdrawals.setVoucherUrl(dto.getVoucherUrl());
                    partnerWithdrawals.setVoucherName(dto.getVoucherName());
                    int updateResult = partnerWithdrawalsMapper.updateByPrimaryKeySelective(partnerWithdrawals);
                    if (updateResult!=1){
                        messageResult.setFailureResult("提交失败，重新提交");
                        return messageResult;
                    }
                    //减去提现金额
                    partnerInfo.setWithdrawalsMoney(partnerInfo.getWithdrawalsMoney().add(partnerWithdrawals.getApplyMoney()));
                    partnerInfo.setFrozenMoney(partnerInfo.getFrozenMoney().subtract(partnerWithdrawals.getApplyMoney()));
                    int updateInfo = partnerInfoMapper.updateByPrimaryKeySelective(partnerInfo);
                    if (updateInfo!=1){
                        messageResult.setFailureResult("提交失败，重新提交");
                        return messageResult;
                    }
                    //添加提现记录
                    PartnerCommission partnerCommission = new PartnerCommission();
                    partnerCommission.setAccountAmount(partnerWithdrawals.getApplyMoney());
                    //3-提现
                    partnerCommission.setSourceGrade(3);
                    partnerCommission.setUserUuid(partnerInfo.getUserUuid());
                    partnerCommission.setGmtCreate(new Date());
                    int insertResult = partnerCommissionMapper.insertSelective(partnerCommission);
                    if (insertResult!=1){
                        messageResult.setFailureResult("提交失败，重新提交");
                        return messageResult;
                    }
                }
            }
        }
        messageResult.setSuccessResult();
        return messageResult;
    }



}
